package com.iot.comprehensive.face.controller;

import com.iot.comprehensive.face.dto.HostInfo;
import com.iot.comprehensive.face.model.Account;
import com.iot.comprehensive.face.model.Host;
import com.iot.comprehensive.face.model.User;
import com.iot.comprehensive.face.service.AccountService;
import com.iot.comprehensive.face.service.HostService;
import com.iot.comprehensive.face.service.ImgPathService;
import com.iot.comprehensive.face.service.UserService;
import com.iot.comprehensive.face.utils.*;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 朱泽玉
 * @Create 2021/7/2 15:21
 * @Description 上传头像
 * @Modified By:
 */
@RestController
@RequestMapping("/host")
@Api(tags = "住户相关", protocols = "http,https")
@ApiResponses({
        @ApiResponse(code = 200, message = "登录成功"),
        @ApiResponse(code = 300, message = "出现错误"),
        @ApiResponse(code = 301, message = "无权限(未认证)")
})
public class HostController {
    final com.iot.comprehensive.face.utils.Jwt jwt;
    final AccountService accountService;
    final HostService hostService;
    final UserService userService;
    final ImgPathService imgPathService;
    final ImgPathController imgPathController;
    String path = "D:/project/zzy/cource/iot/src/main/resources/static/";

    public HostController(Jwt jwt, AccountService accountService, HostService hostService, UserService userService, ImgPathService imgPathService, ImgPathController imgPathController) {
        this.jwt = jwt;
        this.accountService = accountService;
        this.hostService = hostService;
        this.userService = userService;
        this.imgPathService = imgPathService;
        this.imgPathController = imgPathController;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation(value = "上传照片", notes = "以header为用户")
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException {
        Long id = this.getId(request);
        if (id == null) {
            return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
        }
        Account account = accountService.findById(id);
        /***********文件上传操作************/
        //1、获取文件的内容
//        InputStream is = file.getInputStream();
//        inputStream.close();
        //2、以用户账户id为文件夹
        String dirName = Long.toString(id);
        // 3、获取文件夹路径
        String firPath = this.path + dirName;
        File fileDir = new File(firPath);
        //4、若文件夹不存在,则创建出文件夹
        if (fileDir.exists()) {
            File[] delFileList = fileDir.listFiles();
            assert delFileList != null;
            for (File curFile : delFileList) {
                System.out.println(curFile);
                boolean right = curFile.delete();
                System.out.println(right);
            }
        } else {
            fileDir.mkdirs();
        }
        //5、获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //6、根据原始文件名生成文件名
        assert originalFilename != null;
        String uuidFilename = UploadUtils.getUUIDName(originalFilename);
        //7、在文件夹中创建文件
        File newFile = new File(firPath, uuidFilename);
        //8、将文件输出到目标的文件中
        file.transferTo(newFile);
        //将保存的文件路径更新到用户信息headimg中
        String savePath = dirName + "/" + uuidFilename;
        if (account.getIdentity().equals("host")){
            imgPathController.add(account);
        }
        Host host = hostService.findById(id);
//        host.setImg_path();
        return new Result(ResultCode.SUCCESS, savePath);
    }

    @Autowired
    ResourceLoader resourceLoader;

    @RequestMapping(value = "/getimg/{mobile}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
    @ApiOperation(value = "根据mobile获取图片", notes = "")
    public byte[] get(@PathVariable("mobile") String mobile) throws IOException {
        Account account = accountService.findByMobile(mobile);
        long id = account.getId();
        // 4、拼接文件夹目录，并获取文件绝对路径
        String filePath = this.path + id;
        File[] fileList = new File(filePath).listFiles();
        assert fileList != null;
        String tmp = fileList[0].getAbsolutePath();
        // 5、获取图片字节
        File img = new File(tmp);
        FileInputStream inputStream = new FileInputStream(img);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        inputStream.close();
        return bytes;
    }

    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    @ApiOperation(value = "提交申请表", notes = "只需要提交address，图片调用前面接口进行上传")
    public Result apply(HttpServletRequest request, @RequestBody Host form) {
        Long id = this.getId(request);
        if (id == null) {
            return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
        }
        Host hostById = hostService.findById(id);
        if (hostById!=null){
            int state = hostById.getState();
            if (state==1){
                return new Result(ResultCode.UN_LOGIN, "请重新登陆");
            }
            if ( state== 0) {
                return new Result(ResultCode.UN_AUTHORISE, "申请正在审批中，请耐心等待");
            }
            if (state == 2) {
                // 如果是注册失败的重新进行注册则不返回
                if (form.getState()!=2){
                    return new Result(ResultCode.FAIL, hostById);
                }
            }
        }
        Host host = new Host();
        host.setId(id);
        host.setAddress(form.getAddress());
        // 未审核
        host.setState(0);
        hostService.save(host);
        return new Result(ResultCode.SUCCESS);
    }

    @RequestMapping(value = "/apply", method = RequestMethod.PUT)
    @ApiOperation(value = "修改", notes = "用户修改提交address，管理员修改需要提交state不通过的话提交建议，图片调用前面接口进行上传,根据header自动识别身份，")
    public Result applyChange(HttpServletRequest request, @RequestBody Host form) throws IOException {
        System.out.println(form);

        Long id = this.getId(request);
        if (id == null) {
            return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
        }
        String identity = accountService.findById(id).getIdentity();
        Host host = hostService.findById(form.getId());
        Account account = accountService.findById(form.getId());
        // 如果是管理员的话，只能修改状态
        if (identity.equals("admin")) {
            // 如果通过(修改状态，成为正式住户)
            if (form.getState() == 1) {
                host.setDate_time(PatternUtils.GetTime());
                host.setSuggest("通过");
                imgPathController.add(account);
                account.setIdentity("host");
            }else{
                host.setSuggest(form.getSuggest());
            }
            host.setState(form.getState());
        }

        // 如果是普通用户的话，只能修改地址
        if (identity.equals("host")) {
            host.setAddress(form.getAddress());
        }
        hostService.save(host);
        accountService.update(account);
        return new Result(ResultCode.SUCCESS);
    }

    @RequestMapping(value = "/apply", method = RequestMethod.GET)
    @ApiOperation(value = "获取申请表", notes = "管理员获取所有，普通用户和住户均获取个人申请表")
    public Result applyOne(HttpServletRequest request) throws IOException {
        Long id = this.getId(request);
        if (id == null) {
            return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
        }
        String identity = accountService.findById(id).getIdentity();
        if (identity.equals("host") || identity.equals("user")) {
            Host data = hostService.findById(id);
            return new Result(ResultCode.SUCCESS, data);
        }
        if (identity.equals("admin")) {
            List<Host> hostList = hostService.findAll();
            List<HostInfo> hostInfoList = new ArrayList<>();
            for (Host host : hostList) {
                if (host.getState() == 0 || host.getState() == 2) {
                    String hostId = host.getId().toString();
                    HostInfo hostInfo = new HostInfo();
                    User userInfo = userService.getByAccount(host.getId());
                    Account account = accountService.findById(host.getId());
                    hostInfo.setId(hostId);
                    hostInfo.setHost(host);
                    hostInfo.setUser(userInfo);
                    hostInfo.setAccount(account);
                    hostInfoList.add(hostInfo);
                }
            }
            System.out.println(hostInfoList);
            return new Result(ResultCode.SUCCESS, hostInfoList);
        }
        return new Result(ResultCode.FAIL);
    }

    public Long getId(HttpServletRequest request) {
        // 1、获取返回的token
        Claims token = jwt.token(request);
        // 2、判断是否携带token
        if (token == null) {
            return null;
        }
        // 3、获取token中的id值
        return Long.parseLong(token.getId());
    }


    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部住户信息", notes = "管理员获取所有，普通用户和住户均获取个人")
    public Result getAll(HttpServletRequest request) throws IOException {
        Long id = this.getId(request);
        if (id == null) {
            return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
        }
        String identity = accountService.findById(id).getIdentity();
        if (identity.equals("admin")) {
            List<Host> hostList = hostService.findAll();
            List<HostInfo> hostInfoList = new ArrayList<>();
            for (Host host : hostList) {
                if (host.getState() == 1) {
                    HostInfo hostInfo = new HostInfo();

                    User userInfo = userService.getByAccount(host.getId());
                    Account account = accountService.findById(host.getId());
                    hostInfo.setUser(userInfo);
                    hostInfo.setHost(host);
                    hostInfo.setAccount(account);
                    hostInfoList.add(hostInfo);
                }

            }
            return new Result(ResultCode.SUCCESS, hostInfoList);
        }
        return new Result(ResultCode.UN_AUTHORISE);
    }



}
